﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.RemoteEventBus;
using Abp.Runtime.Caching;
using Castle.Core.Logging;
using FwProject.Authorization.Users;
using FwProject.Comm;
using FwProject.Core.Distribution;
using FwProject.Core.Restaurant;
using FwProject.Distribution;
using FwProject.Distribution.Dto;
using FwProject.JPush.JPushModel;
using FwProject.PublicService.JPush;
using FwProject.Restaurant;
using FwProject.Users;
using Microsoft.EntityFrameworkCore;

namespace FwProject.RemoteEventBus
{

    [RemoteEventHandler(ForType = RemoteTypeHelp.TypeLoadCarPushMessage, ForTopic = RemoteTypeHelp.TopicLoadCar)]
    public class PushLoadCarMessage : IRemoteEventHandler, ITransientDependency
    {
        public readonly ICacheManager _catchmanager;
        public readonly IJPushAppservice _jPushAppservice;
        public readonly IUserAppService _userAppService;
        public readonly IRepository<LoadCar, Guid> _repositoryLoadCar;
        private readonly IRepository<User, long> _userRepository;
        public ILogger logging { get; set; }
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public PushLoadCarMessage(ICacheManager catchmanager, IJPushAppservice jPushAppservice,
                                        IRepository<LoadCar, Guid> repositoryLoadCar,
                                         IUserAppService userAppService,
                                          IRepository<User, long> userRepository,
                                          IUnitOfWorkManager unitOfWorkManager
                                          )
        {
            _userRepository = userRepository;
            _repositoryLoadCar = repositoryLoadCar;
            _catchmanager = catchmanager;
            _jPushAppservice = jPushAppservice;
            logging = NullLogger.Instance;
            _userAppService = userAppService;
            _unitOfWorkManager = unitOfWorkManager;

        }
        [UnitOfWork]
        public void HandleEvent(RemoteEventArgs eventArgs)
        {
            logging.Info($"{nameof(PushLoadCarMessage)}车辆状态：{CarStatus.出库审核中}==出库状态: {ExamineStatus.已审核}===回库状态{BackStatus.已审核}");
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                try
                {
                    var t = _repositoryLoadCar.GetAllIncluding(o => o.CarInfoModel);
                    var loadCarModel = t.Where(o => o.Id == Guid.Parse(eventArgs.EventData.Data[RemoteTypeHelp.MODELID].ToString())).FirstOrDefault();

                    LoadCarPushMessageModel loadCarPushMessage = new LoadCarPushMessageModel();
                    if (loadCarModel.CarStatus == CarStatus.出库审核中)
                    {
                        var usercar = _userRepository.Get(loadCarModel.DriverUserId.Value);
                        ///获取餐厅信息
                        loadCarPushMessage.Id = loadCarModel.Id;
                        loadCarPushMessage.UserId = loadCarModel.CreatorUserId.Value;
                        loadCarPushMessage.TopicModel = JPush.JPushHelpel.TopicAppSystemKG;
                        _jPushAppservice.RestaurantPushMessage($"{usercar.FactoryinfoId.Value.ToString().Replace("-", "")}KG", loadCarPushMessage, $"{loadCarModel.CarInfoModel.PlatesNumber}已装车完成请立即审核");
                    }
                    if (loadCarModel.ExamineStatus == ExamineStatus.已审核 && loadCarModel.CarStatus == CarStatus.配送中 && loadCarModel.BackStatusOverTime == null)
                    {
                        ///获取餐厅信息
                        var usercar = _userRepository.Get(loadCarModel.DriverUserId.Value);
                        loadCarPushMessage.Id = loadCarModel.Id;
                        loadCarPushMessage.UserId = loadCarModel.DriverUserId.Value;
                        _jPushAppservice.RestaurantPushMessage(usercar.Mobile, loadCarPushMessage, $"（库管）已确认装车可以配送");
                    }
                    if (loadCarModel.CarStatus == CarStatus.配送中 && loadCarModel.BackStatusOverTime != null)
                    {
                        ///获取餐厅信息
                        var usercar = _userRepository.Get(loadCarModel.DriverUserId.Value);
                        loadCarPushMessage.Id = loadCarModel.Id;
                        loadCarPushMessage.UserId = loadCarModel.DriverUserId.Value;
                        _jPushAppservice.RestaurantPushMessage(usercar.Mobile, loadCarPushMessage, $"（库管）退回盘点，详情请联系库管");
                    }
                    if (loadCarModel.CarStatus == CarStatus.回库审核中)
                    {
                        ///获取餐厅信息
                        var usercar = _userRepository.Get(loadCarModel.DriverUserId.Value);

                        loadCarPushMessage.Id = loadCarModel.Id;
                        loadCarPushMessage.UserId = loadCarModel.DriverUserId.Value;
                        loadCarPushMessage.TopicModel = JPush.JPushHelpel.TopicAppSystemKG;
                        _jPushAppservice.RestaurantPushMessage($"{usercar.FactoryinfoId.Value.ToString().Replace("-", "")}KG", loadCarPushMessage, $"{loadCarModel.CarInfoModel.PlatesNumber}已配送完成请立即审核");
                    }
                    if (loadCarModel.BackStatus == BackStatus.已审核)
                    {
                        ///获取餐厅信息
                        var usercar = _userRepository.Get(loadCarModel.DriverUserId.Value);
                        loadCarPushMessage.Id = loadCarModel.Id;
                        loadCarPushMessage.UserId = loadCarModel.DriverUserId.Value;
                        _jPushAppservice.RestaurantPushMessage($"{usercar.Mobile}", loadCarPushMessage, $"(库管)已完成回库审核。");
                    }
                    unitOfWork.Complete();
                }
                catch (Exception exe)
                {
                    logging.Error($"{nameof(PushLoadCarMessage)}", exe);

                }
                finally
                {
                    logging.Info($"{nameof(PushLoadCarMessage)}");
                }

             
            }
        }
    }

}
